<%= form_for Post.new, :remote => true do |f| %>
  <div class="form-group">
    <%= f.text_area :content, :class => "form-control" %>
  </div>
  <div class="form-group">
    <%= f.submit :class => 'btn btn-primary' %>
  </div>
<% end %>

<div id="post-list">
<% @posts.each do |p| %>
  <%= render :partial => "post", :locals => {:post => p} %>
<% end %>
</div>

<script>
  var post_id_set = new Set();
  var current_post_id = <%= @posts.last.id %>;

  $(window).scroll(function(){

    function loadData() {
      var url = "/posts?max_id=" + current_post_id;
      if (url && !post_id_set.has(current_post_id)) {
        $.ajax({
          method: "GET",
          url: url,
          dataType: "script"
        });
        post_id_set.add(current_post_id)
        console.log("get max_id=" + current_post_id);
      } else {
        console.log("repeat request or data ended")
      }
    };
    if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
      loadData()
    }

  })

  //delete
  $(".delete-post").click(function(event){

    console.log("1. prevent default event");
    event.preventDefault();
    var url = $(this).attr("href");

    console.log(" url: "+ url);

    $.ajax({
      url: url,
      method: 'DELETE',
      dataType: 'json',
      success: function(data){
        $("#post-" + data["id"]).remove();
      }
    });
    console.log("2. call $.ajax");
  })
</script>
